package com.hsogoo.avatar.transport.netty.handler;

import com.hsogoo.avatar.model.AvatarRequest;
import com.hsogoo.avatar.model.AvatarResponse;
import com.hsogoo.avatar.transport.AvatarProcessor;
import com.hsogoo.avatar.utils.StackTraceUtil;
import io.netty.channel.Channel;
import io.netty.channel.ChannelConfig;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.util.ReferenceCountUtil;
import lombok.extern.slf4j.Slf4j;

/**
 * @Author huangsaigang
 * Created @2018/9/29.
 */
@Slf4j
public class AvatarConnectorHandler extends ChannelInboundHandlerAdapter {

    private AvatarProcessor processor;

    public AvatarConnectorHandler() {
    }

    public AvatarConnectorHandler(AvatarProcessor processor) {
        this.processor = processor;
    }

    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        Channel ch = ctx.channel();
        if (msg instanceof AvatarResponse) {
            try {
                processor.processResponse((AvatarResponse) msg);
            } catch (Throwable t) {
                log.error("process response exception...");
            }
        } else {
            log.warn("Unexpected message type received: {}, channel: {}.", msg.getClass(), ch);
            ReferenceCountUtil.release(msg);
        }
        ctx.close();
    }


    @Override
    public void channelWritabilityChanged(ChannelHandlerContext ctx) throws Exception {
        Channel ch = ctx.channel();
        ChannelConfig config = ch.config();
        if (!ch.isWritable()) {
            config.setAutoRead(false);
        } else {
            config.setAutoRead(true);
        }
    }

    @Override
    public void userEventTriggered(ChannelHandlerContext ctx, Object evt) throws Exception {
        super.userEventTriggered(ctx, evt);
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        Channel ch = ctx.channel();
        log.error("Unexpected exception was caught: {}, channel: {}.", StackTraceUtil.stackTrace(cause), ch);
        ch.close();
    }

}
